import time
import os
import cv2
from screen_capture import capture_screen
from template_matching import load_template, match_template
from input_control import click_at_position, press_key
from config import SCREENSHOT_REGION, TEMPLATE_PATH, MATCH_THRESHOLD, CHECK_INTERVAL, DEBUG_MODE, DEBUG_OUTPUT_DIR

class GameAutoPlot:
    def __init__(self):
        """初始化游戏自动化脚本"""
        self.running = False
        self.templates = {}
        self.load_templates()
        
        # 创建调试目录
        if DEBUG_MODE and not os.path.exists(DEBUG_OUTPUT_DIR):
            os.makedirs(DEBUG_OUTPUT_DIR)

    def load_templates(self):
        """加载所有模板图片"""
        if not os.path.exists(TEMPLATE_PATH):
            print(f"模板目录不存在: {TEMPLATE_PATH}")
            return
            
        for filename in os.listdir(TEMPLATE_PATH):
            if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
                try:
                    template_name = os.path.splitext(filename)[0]
                    self.templates[template_name] = load_template(filename)
                    print(f"已加载模板: {template_name}")
                except Exception as e:
                    print(f"加载模板 {filename} 失败: {e}")

    def check_for_targets(self, screen_image):
        """
        检查屏幕截图中是否存在目标图标
        
        Args:
            screen_image (numpy.ndarray): 屏幕截图
            
        Returns:
            list: 匹配结果列表 [(模板名, 匹配位置, 置信度), ...]
        """
        matches = []
        
        for template_name, template_image in self.templates.items():
            try:
                is_match, position, confidence = match_template(
                    screen_image, template_image, MATCH_THRESHOLD
                )
                
                if is_match:
                    matches.append((template_name, position, confidence))
                    
                    # 调试模式下保存标记了匹配位置的图片
                    if DEBUG_MODE:
                        debug_image = screen_image.copy()
                        if position:
                            # 在匹配位置画一个圆圈
                            cv2.circle(debug_image, position, 20, (0, 255, 0), 3)
                            # 添加置信度文本
                            cv2.putText(debug_image, f"{template_name}: {confidence:.2f}", 
                                       (position[0], position[1] - 10),
                                       cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
                        
                        # 保存调试图片
                        debug_filename = f"{DEBUG_OUTPUT_DIR}debug_{template_name}_{int(time.time())}.png"
                        cv2.imwrite(debug_filename, debug_image)
                        
            except Exception as e:
                print(f"匹配模板 {template_name} 时出错: {e}")
                
        return matches

    def perform_action(self, template_name, position):
        """
        根据匹配的模板执行相应的操作
        
        Args:
            template_name (str): 模板名称
            position (tuple): 匹配位置
        """
        print(f"检测到目标图标: {template_name} (置信度: {0})")
        
        # 根据模板名称执行不同的操作
        if "dialog" in template_name.lower() or "confirm" in template_name.lower():
            # 对话框确认操作
            if position:
                click_at_position(position[0], position[1])
            else:
                # 如果没有具体位置，则点击默认位置
                click_at_position(SCREENSHOT_REGION[0] + SCREENSHOT_REGION[2] // 2,
                                SCREENSHOT_REGION[1] + SCREENSHOT_REGION[3] // 2)
        else:
            # 默认操作：按空格键
            press_key()

    def start(self):
        """启动自动化脚本"""
        print("原神自动剧情脚本启动")
        print("请确保游戏窗口在前台运行")
        print("按Ctrl+C停止脚本")
        
        self.running = True
        
        try:
            while self.running:
                # 捕获屏幕
                screen_image = capture_screen(SCREENSHOT_REGION)
                
                # 检查目标图标
                matches = self.check_for_targets(screen_image)
                
                # 处理匹配结果
                for template_name, position, confidence in matches:
                    self.perform_action(template_name, position)
                
                # 等待下次检查
                time.sleep(CHECK_INTERVAL)
                
        except KeyboardInterrupt:
            print("\n脚本已停止")
        except Exception as e:
            print(f"脚本运行出错: {e}")
        finally:
            self.stop()

    def stop(self):
        """停止自动化脚本"""
        self.running = False
        print("原神自动剧情脚本已停止")

def main():
    """主函数"""
    auto_plot = GameAutoPlot()
    
    # 创建必要的目录
    if not os.path.exists(TEMPLATE_PATH):
        os.makedirs(TEMPLATE_PATH)
        print(f"已创建模板目录: {TEMPLATE_PATH}")
        print("请将目标图标模板图片放入此目录后再运行脚本")
        return
    
    # 检查是否有模板图片
    template_files = [f for f in os.listdir(TEMPLATE_PATH) 
                     if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
    
    if not template_files:
        print("未找到模板图片，请将目标图标模板图片放入 templates 目录")
        return
    
    # 启动自动化脚本
    auto_plot.start()

if __name__ == "__main__":
    main()